<?php
namespace App\Modules\Admin\Services;

use App\Modules\Admin\Interfaces\CurdServiceInterface;
use Illuminate\Container\Container;
use Exception;
use Illuminate\Support\Facades\Log;

class AdminService implements CurdServiceInterface
{
    protected $queryBuilder;

    protected $model;

    public function getQueryBuilder(array $data) {}

    public function getTree(array $data) {}


    public function page($data)
    {
        static::getQueryBuilder($data);
        return $this->queryBuilder->paginate($data['page_size'] ?? 15);
    }

    public function justGet($data)
    {
        static::getTree($data);

        // dd($this->queryBuilder->toSql());
        return $this->queryBuilder->get();
    }

    public function add(Array $data)
    {
        Log::info('data: ', $data);
        return $this->getModel()->create($data);
    }

    public function edit(Int $id, Array $data)
    {
        $model = $this->getModel()->find($id);
        $model->update($data);
        if($model->isDirty()) {
            $model->touch();
        }
        return $model;
    }

    public function del(Int|String $id)
    {
        $ids = explode(',', $id);
        return $this->getModel()->destroy($ids);
    }

    public function detail(Int $id)
    {
        return $this->getModel()->find($id);
    }

    public function getModel()
    {
        try {
            return Container::getInstance()->make($this->model);
        } catch(Exception) {
            return response()->json(['msg' => '操作失败' , 'code' => 30502]);
        }
    }
}